package com.codingman.data.mybatis.support;

import java.util.Collection;
import java.util.Iterator;

import org.apache.ibatis.builder.annotation.ProviderContext;
import org.apache.ibatis.builder.annotation.ProviderMethodResolver;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.util.CollectionUtils;

public class SelectSqlProvider extends BaseSqlProviderSupport implements ProviderMethodResolver{
	
	public String findById(ProviderContext context) {
		Class<?> entityClass = getEntityClass(context);
		TableInfo table = TableInfo.forClass(entityClass);
		return new SQL().SELECT(this.getColumns(table))
				.FROM(table.getName())
				.WHERE(table.getPKConlumn() + " = #{id}")
				.toString();
	}
	
	public String findAll(ProviderContext context) {
		Class<?> entityClass = getEntityClass(context);
		TableInfo table = TableInfo.forClass(entityClass);
		return new SQL().SELECT(this.getColumns(table))
				.FROM(table.getName())
				.toString();
	}
	
	public String count(ProviderContext context) {
		Class<?> entityClass = getEntityClass(context);
		TableInfo table = TableInfo.forClass(entityClass);
		return new SQL().SELECT("COUNT(1)")
				.FROM(table.getName())
				.toString();
	}
	
	public String getColumns(TableInfo table) {
		Collection<String> columns = table.getColumns();
		if (CollectionUtils.isEmpty(columns)) {
			return "";
		}
		Iterator<String> iterator = columns.iterator();
		StringBuilder sb = new StringBuilder();
		while (iterator.hasNext()) {
			String next = iterator.next();
			sb.append(next);
			if (iterator.hasNext()) {
				sb.append(", ");
			}
		}
		return sb.toString();
	}
}
